#include "ChannelSubscribable.hpp"

ChannelSubscribable::ChannelSubscribable()
	:mCreator(nullptr)
{
	zeroMembers();
}

ChannelSubscribable::~ChannelSubscribable()
{
	clearThis();
}

void ChannelSubscribable::clearThis()
{
	mCreator = nullptr;

	mSubscribers.clear();

	zeroMembers();
}

void ChannelSubscribable::zeroMembers()
{
	// do nothing.
}

void ChannelSubscribable::clear()
{
	clearThis();
}

void ChannelSubscribable::setCreator(SocketBasePtr pCreator)
{
	mCreator = pCreator;
}

SocketBasePtr ChannelSubscribable::getCreator() const
{
	return mCreator;
}

void ChannelSubscribable::addSubscriber(SocketBasePtr pSocket)
{
	if (pSocket == nullptr)
	{
		return;
	}

	mSubscribers.insert(pSocket);
}

void ChannelSubscribable::removeSubscriber(SocketBasePtr pSocket)
{
	if (pSocket == nullptr)
	{
		return;
	}

	auto it = mSubscribers.find(pSocket);
	if (it == mSubscribers.end())
	{
		return;
	}

	mSubscribers.erase(it);
}

void ChannelSubscribable::dispatch(const Message& msg)
{
	for (auto it = mSubscribers.begin(); it != mSubscribers.end(); ++it)
	{
		Message msgClone = msg;
		(*it)->send(std::move(msgClone));
	}
}

void ChannelSubscribable::EnableBroadCast(bool bEnable) 
{ 
	mIsBroadCast = bEnable; 
}
